<template>
    <view id="container" class="container-c">
        <view
            v-for="(item, index) in list"
            :id="'tab' + index"
            :class="['tab', active == index ? 'active' : '']"
            @click="onTab(index)"
            :key="index"
        >
            <view>
                {{ item.title }}
                <!-- <text class="num" v-if="item.num">{{ item.num }}</text> -->
            </view>
        </view>
        <view class="current-active" :animation="animationData" />
    </view>
</template>

<script lang="ts" setup>
import { ref, watch, defineEmits, getCurrentInstance } from 'vue'
const props = defineProps(['active', 'list'])
const emit = defineEmits(['change', 'update:active'])
const page = getCurrentInstance()
const animation = uni.createAnimation()
const active = ref(props.active)
const animationData = ref({})

watch(
    () => props.active,
    (index: number) => {
        navigateTo(index)
    }
)

const onTab = (index: number) => {
    emit('change', index)
    emit('update:active', index)
    active.value = index
    navigateTo(index)
}
const getElementWidth = (
    ele: string
): Promise<{
    width: number
    left: number
}> => {
    return new Promise(resolve => {
        const selector = uni.createSelectorQuery()
        selector.in(page)
        selector.select(ele).boundingClientRect(res => {
            resolve({
                width: res.width as number,
                left: res.left as number
            })
        })
        selector.exec()
    })
}
const navigateTo = async (index: number) => {
    animationData.value = {}
    const ele = await getElementWidth('#tab' + index)
    const container = await getElementWidth('#container')
    animation.translateX(ele.left + ele.width / 2 - container.left - 8).step({
        duration: 200
    })
    animationData.value = animation.export()
}

navigateTo(props.active)
</script>

<style lang="scss">
.container-c {
    position: relative;
    display: flex;
    align-items: center;
    color: $uni-text-color-grey;
    font-size: $uni-font-size-h4;
    padding-top: 20rpx;
    padding-bottom: 20rpx;

    .active {
        font-weight: bold;
        color: rgba(32, 37, 54, 1);
        // font-size: $uni-font-size-lg;
    }

    .current-active {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 36rpx;
        height: 8rpx;
        background: #3E5FF5;
        border-radius: 3rpx;
    }
}

.tab {
    margin-right: 30rpx;
    flex-shrink: 0;
}
.num {
    font-size: 24rpx;
    color: #9497b1;
    margin: 0 0 10rpx 10rpx;
}
</style>
